package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.exception.LogicException;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.redis.vo.StrategyStatisVO;
import cn.wolfcode.wolf2w.repository.UserInfoRepository;
import cn.wolfcode.wolf2w.service.IUserInfoService;
import cn.wolfcode.wolf2w.util.Consts;
import cn.wolfcode.wolf2w.util.MD5util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.wolfcode.wolf2w.util.Assert;

import java.util.List;
import java.util.UUID;

@Service
public class UserInfoServiceImpl implements IUserInfoService {

    @Autowired
    private UserInfoRepository repository;

    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    @Override
    public void save(UserInfo userInfo) {
        userInfo.setId(null);
        repository.save(userInfo);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public void update(UserInfo userInfo) {
        repository.save(userInfo);
    }

    @Override
    public UserInfo get(String id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<UserInfo> listAll() {
        return repository.findAll();
    }

    @Override
    public boolean checkPhone(String phone) {
        UserInfo user = repository.findByPhone(phone);
        return user != null;
    }

   /* @Value("sms.url")
    private String url;*/
   /* @Value("sms.sign")
    private String sign;*/
   /* @Value("sms.appkey")
    private String appkey;*/

    @Override
    public void sendVerifyCode(String phone) {

        //生成四位随机数验证码
        String code = UUID.randomUUID().toString().replaceAll("-","").substring(0,4);
        //生成短信
        StringBuilder sb = new StringBuilder();
        sb.append("【叩丁狼】你的验证码是：").append(code).append(",请在")
                .append(Consts.VERIFY_CODE_VAI_TIME).append("分钟之内完成验证");

        //模拟短信发送成功
        System.out.println(sb);

        // 真实发送短信
        //Url:https://way.jd.com/kaixintong/kaixintong?mobile=18276918240&content=【凯信通】您的验证码是：123456&appkey=ced6bfafa64238323c90586b380d45b7
      /*  RestTemplate rest = new RestTemplate();
        String url = "https://way.jd.com/chonry/GET?mobile={1}&content={2}&appkey={3}";
        //String sign = "【叩丁狼】";
        String appkey = "ced6bfafa64238323c90586b380d45b7";
        // 参数1：请求url,参数2：响应结果封装成对象类型,参数3：请求携带参数
        String ret = rest.getForObject(url, String.class, phone, sb.toString(), appkey);
        System.out.println(ret);
        if(!ret.contains("SUCCESS")){
            throw new LogicException("短信发送失败");
        }*/
        //把验证码缓存到redis中
        userInfoRedisService.setVerifyCode(phone,code);

        Long time = userInfoRedisService.getCodeTime(phone);
        if(time < 10) {
            throw new LogicException("10秒钟之内不允许重复发送短信");
        }else {
            userInfoRedisService.setVerifyCode(phone, code);
        }
    }

    @Override
    public void regist(String phone, String nickname, String password, String rpassword, String verifyCode) {
        // 判断传入是否为空
        Assert.hasText(phone,"手机号不能为空");
        Assert.hasText(nickname,"昵称不能为空");
        Assert.hasText(password,"密码不能为空");
        Assert.hasText(rpassword,"确认密码不能为空");
        Assert.hasText(verifyCode,"短信验证码不能为空");
        // 判断两次输入密码是否相等
        Assert.isEquals(password,rpassword,"两次输入密码不一致");
        // 手机号码格式必须正确 @TODO java正则表达式

        // 手机号必须进行唯一效验
        if(checkPhone(phone)){
            Assert.hasText(phone,"手机号已经被注册");
        }
        // 短信验证码必须一致
        String code = userInfoRedisService.getVerifyCode(phone);
        if(!code.equalsIgnoreCase(verifyCode)){
            Assert.isEquals(code,verifyCode,"验证码失效或验证码错误");
        }
        // 注册
        UserInfo userInfo = new UserInfo();
        userInfo.setNickname(nickname);
        userInfo.setPhone(phone);
        userInfo.setEmail("");
        userInfo.setPassword(String.valueOf(MD5util.code(password,nickname)));
        userInfo.setCity("");
        userInfo.setHeadImgUrl("/images/default.png");
        userInfo.setInfo("");
        userInfo.setState(UserInfo.STATE_NORMAL);
        //模拟系统异常
        //throw new RuntimeException("bfehfruehjfvb ldhfrgo;dj'kxsbh cvghuwidofkvgbfvdepfvb cnjxksaocdsasxcdvb c");
        this.save(userInfo);
    }

    @Override
    public UserInfo login(String username, String password) {
        // 判断传入是否为空
        Assert.hasText(username,"用户名不能为空");
        Assert.hasText(password,"登录密码不能为空");
        // 登录效验
        UserInfo user = repository.findByPhone(username);
        if(user == null || !user.getPassword().equals(String.valueOf(MD5util.code(password,user.getNickname())))){
            throw new LogicException("用户名或密码错误");
        };
        return user;
    }

    @Override
    public List<UserInfo> getByCity(String city) {
        return repository.findByCity(city);
    }
}
